from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from xml.dom.minidom import parse, parseString

from models.project import MasterControlProject

from settings import *
from utilities import *
import logging

class SubProjectActivityHookHandler(webapp.RequestHandler):
    def post(self, mcp_code):
        mcp = MasterControlProject.get_by_key_name(mcp_code)
        if not mcp:
            return
        
        activityDocument = parseString(self.request.body)
        subproject_id = activityDocument.getElementsByTagName('project_id')[0].firstChild.data
        
        subproject = mcp.subprojects.filter('pivotal_project_id =', int(subproject_id)).get()
        if not subproject:
            return
        
        event_type = activityDocument.getElementsByTagName('event_type')[0].firstChild.data.strip()
        
        for story in activityDocument.getElementsByTagName('story'):        
            other_id_tags = story.getElementsByTagName('other_id')
            if not other_id_tags:
                if event_type == 'story_create':
                    if story.getElementsByTagName('lighthouse_id') or story.getElementsByTagName('lighthouse_url'):
                        continue
                    story_id = story.getElementsByTagName('id')[0].firstChild.data.strip()
                    RemoveTags(story, 'id', 'other_id', 'url', 'other_url', 'integration_id', 'requested_by')
                    owner_tag = story.getElementsByTagName('owned_by')
                    if owner_tag:
                        owner_tag = owner_tag[0]
                        if owner_tag.firstChild:
                            owner_tag.firstChild.data = subproject.owning_user_name
                        else:
                            owner_tag.appendChild(owner_tag.ownerDocument.createTextNode(subproject.owning_user_name))
                    else:
                        owner_tag = story.ownerDocument.createElement('owned_by')
                        owner_tag.appendChild(story.ownerDocument.createTextNode(subproject.owning_user_name))
                        story.appendChild(owner_tag)
                    labels_tag = story.getElementsByTagName('labels')
                    if labels_tag:
                        labels_tag = labels_tag[0]
                        if labels_tag.firstChild:
                            labels_tag.firstChild.data += "," + subproject.label
                        else:
                            labels_tag.appendChild(laebls_tag.ownerDocument.createTextNode(subproject.label))
                    else:
                        labels_tag = story.ownerDocument.createElement('labels')
                        labels_tag.appendChild(story.ownerDocument.createTextNode(subproject.label))
                        story.appendChild(labels_tag)
                    new_story = CreateStory(mcp.pivotal_project_id, mcp.token, story.toxml())
                    logging.info('made new story: ')
                    logging.info(new_story)
                    master_story_id = new_story.getElementsByTagName('id')[0].firstChild.data.strip()
                    project = GetProject(subproject.pivotal_project_id, subproject.token or mcp.token)
                    integration_id = None
                    for integration in project.getElementsByTagName('integration'):
                        name = integration.getElementsByTagName('name')[0].firstChild.data.strip()
                        if name.lower() == subproject.integration_name.strip().lower():
                            integration_id = integration.getElementsByTagName('id')[0].firstChild.data.strip()
                    if integration_id:
                        document = '<story><other_id>%s</other_id><integration_id>%s</integration_id></story>' % (master_story_id, integration_id)
                    else:
                        document = '<story><other_id>%s</other_id></story>' % (master_story_id, )
                    return UpdateStory(subproject.pivotal_project_id, story_id, subproject.token or mcp.token, document)
                else:
                    continue
            
            master_story_id = other_id_tags[0].firstChild.data
            
            if event_type == 'story_create':
                story_id = story.getElementsByTagName('id')[0].firstChild.data.strip()
                master_story = GetStory(mcp.pivotal_project_id, master_story_id, mcp.token)
                labels = master_story.getElementsByTagName('labels')
                if labels and labels[0].firstChild:
                    labels = labels[0].firstChild.data.split(',')
                else:
                    labels = []
                labels.append(subproject.label)
                document = '<story><owned_by>%s</owned_by><labels>%s</labels></story>' % (subproject.owning_user_name, ",".join(labels))
                UpdateStory(mcp.pivotal_project_id, master_story_id, mcp.token, document)
                labels.remove(subproject.label)
                document = '<story><labels>%s</labels></story>' % (",".join(labels), )
                UpdateStory(subproject.pivotal_project_id, story_id, subproject.token or mcp.token, document)
                for note in master_story.getElementsByTagName('note'):
                    author = note.getElementsByTagName('author')
                    if author:
                        author = author[0].firstChild.data.strip()
                    else:
                        author = 'Master Backlog'
                    note = note.getElementsByTagName('text')[0].firstChild.data.strip()
                    note = '%s said: %s' % (author, note)
                    AddComment(subproject.pivotal_project_id, story_id, subproject.token or mcp.token, note)
            elif event_type == 'story_update':
                RemoveTags(story, 'id', 'other_id', 'url', 'other_url', 'integration_id', 'owned_by', 'requested_by', 'created_at')
                labels = story.getElementsByTagName('labels')
                if labels:
                    if labels[0].firstChild:
                        labelarray = labels[0].firstChild.data.split(',')
                    else:
                        labelarray = []
                    labelarray.append(subproject.label)
                    labelarray = sorted(labelarray)
                    if labels[0].firstChild:
                        labels[0].firstChild.data = ",".join(labelarray)
                    else:
                        labels[0].appendChild(labels[0].ownerDocument.createTextNode(','.join(labelarray)))
                UpdateStory(mcp.pivotal_project_id, master_story_id, mcp.token, story)
            elif event_type == 'story_delete':
                master_story = GetStory(mcp.pivotal_project_id, master_story_id, mcp.token)
                labels = master_story.getElementsByTagName('labels')
                if labels and labels[0].firstChild:
                    labels = labels[0].firstChild.data.split(',')
                    if subproject.label in labels:
                        labels.remove(subproject.label)
                    for label in subproject.old_labels:
                        if label in labels:
                            labels.remove(label)
                    labels = sorted(labels)
                else:
                    labels = []
                document = '<story><owned_by></owned_by><labels>%s</labels></story>' % (",".join(labels), )
                UpdateStory(mcp.pivotal_project_id, master_story_id, mcp.token, document)
            elif event_type == 'note_create':
                note = story.getElementsByTagName('text')[0].firstChild.data.strip()
                author = activityDocument.getElementsByTagName('author')[0].firstChild.data.strip()
                AddComment(mcp.pivotal_project_id, master_story_id, mcp.token, '%s said: %s' % (author, note))
        try:
            if mcp.activities_processed:
                mcp.activities_processed += 1
            else:
                mcp.activities_processed = 1
            mcp.put()
            if subproject.activities_processed:
                subproject.activities_processed += 1
            else:
                subproject.activities_processed = 1
            subproject.put()
        except Exception, e:
            logging.info(e)
            pass